<template>
    <div class="room">
      <div class="view" ref="scrollContainer">
        <div v-for="item in messageList">
          <!-- 系统通知消息 -->
          <div class="notice" v-if="item.id === -1">{{ item.message }}</div>
          <!-- 其他用户的消息 -->
          <div class="other" v-else-if="item.id !== 0">
            <div class="hImg">
              <img style="border-radius: 6px;" src="../../assets/picture/aiAvatar.jpg">
            </div>
            <div>
              <p style="margin-left: 10px; font-size: smaller;">小超</p>
              <div class="message">{{ item.message }}
                <!-- 添加播放按钮 -->
                <el-button
                 type="text"
                 @click="playSpeech(item.message)"
                 :icon="VideoPlay"
                 class="play-btn"
                />
                <span>{{ item.createTime }}</span>
              </div>
              
              
            </div>
          </div>
          <!-- 当前用户的消息 -->
          <div class="me" v-if="item.id==0">
            <div>
              <p style="font-size: smaller; text-align: right; margin-right: 10px;">{{ user.username }}</p>
              <div class="message">{{ item.message }}</div>
            </div>
            <div class="hImg">
              <img style="border-radius: 6px;" :src="user.avatar">
            </div>
          </div>
        </div>
      </div>
      <div class="input">
        <el-input type="textarea" placeholder="请输入..." :autosize="{ minRows: 7, maxRows: 7 }" resize="none" style="width: 100%; float: left;" v-model.trim="input" @keyup.enter="send"/>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="发送"
          placement="top"
        >
          <el-button class="input-anniu" @click="send">
            <el-icon><Position /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="tooltipContent"
          placement="top"
        >
          <el-button  class="input-anniu" @click="toggleVoice">
            <el-icon>
              <!-- <Microphone /> -->
              <!-- 根据 isRecording 状态切换图标 -->
              <component :is="recordingIcon" />
            </el-icon>
          </el-button>
        </el-tooltip>
    
      </div>
    </div>


<!--     
  <div  class="bo" v-if="bo">
      <div ref="recwave" style="height: 100%; width: 100%"></div>
  </div> -->

  <div v-if="isRecording && !isPaused" class="recording-animation">
      正在 <br> 说话
    </div>
  </template>
  
<script setup>
  import { ref, onMounted, onUnmounted, watch, onUpdated, markRaw  } from 'vue'
  import useCounter from '../../stores/pinia'
  import { parseJwt } from '../../stores/pinia'
  import { ElMessage, ElNotification } from 'element-plus'
  import { useRouter } from 'vue-router';
  import { Microphone, Mic } from '@element-plus/icons-vue';
  import { sendAudioAPI,getChatAPI} from '@/api/ai.js'
  import Recorder from 'recorder-core';
  import 'recorder-core/src/engine/mp3';
  import 'recorder-core/src/engine/mp3-engine';
  import 'recorder-core/src/engine/wav';
  import 'recorder-core/src/extensions/waveview';
  import Speech from 'speak-tts'
  import { VideoPlay } from '@element-plus/icons-vue'


  const bo=ref(false)
  const input = ref("")
  const router = useRouter()
  const messageList = ref([])
  const counterStore = useCounter()
  const mesId = ref(1)
  const user = ref({
    id: null,
    username: '',
    avatar: 'https://www.toopic.cn/public/uploads/small/169139790585716913979057.jpg'
  })

  let speechInstance;
  const initSpeech = () => {
    const speech = new Speech();
    speech.init({
      volume: 0.5,
      lang: 'en-GB',
      rate: 1,
      pitch: 1,
    }).catch(e => {
      console.error('初始化时发生错误:', e);
    });
  
    speechInstance = speech;
  }

  // 播放语音
  const playSpeech = (text) => {
    speechInstance.setLanguage("zh-CN");
    speechInstance.setVoice("Microsoft Xiaoxiao Online (Natural) - Chinese (Mainland)");
    speechInstance.speak({
      text: text,
      queue: false,
    }).catch(e => {
      console.error('发生错误:', e);
    });
  }

  // 发送消息
  const send = async() => {
    if(input.value!=null&&input.value!=""){
      let params={
      message:input.value,
      userId:user.value.id
      }
      // const eventSource = new EventSource(`http://localhost:8080/chat?message=${encodeURIComponent(input.value)}&userId=${user.value.id}`);
      const eventSource =await getChatAPI(params);

      // console.log(eventSource)

      mesId.value=mesId.value+1

      messageList.value.push({id:0,message:input.value,avatar:user.value.avatar})

      input.value=""
      
      let resultString = eventSource.data.replace(/data:/g, '').replace(/\n\ndata:/g, '').replace(/\s+/g, '').replace(/responseEnd/g,'');
      // console.log(resultString);

            const existingItemIndex=messageList.value.findIndex(item=>item.id ===mesId.value)

      if(resultString !="responseEnd"){
      if(existingItemIndex !==-1){
          messageList.value[existingItemIndex].message+= resultString
      }else{
          messageList.value.push({id:mesId.value,message:resultString})
      }
      }

      // 处理模型响应
      // eventSource.onmessage = (event) => {
      //   console.log("大模型：", event.data);
      // //   huida.value=huida.value+event.data


      //     const existingItemIndex=messageList.value.findIndex(item=>item.id ===mesId.value)

      //     if(event.data !="responseEnd"){
      //     if(existingItemIndex !==-1){
      //         messageList.value[existingItemIndex].message+= `${event.data}`
      //     }else{
      //         messageList.value.push({id:mesId.value,message:event.data})
      //     }
      // }

      //   if(event.data==="responseEnd"){
      //     console.log("传输结束",messageList.value)
      //       eventSource.close();
      //   }
      // //   huida.value.push(event.data); // 直接push新消息而不是使用push方法尝试改变字符串
      // };

      // eventSource.onerror = () => {
      // console.error('SSE错误:');
      //   // 检查是否有可用的错误信息
      //   if (event.target.readyState === EventSource.CLOSED) {
      //       console.error('连接被关闭');
      //   } else if (event.target.readyState === EventSource.CONNECTING) {
      //       console.error('正在尝试重新连接');
      //   } else {
      //       // 尝试获取更多信息
      //       let errorMessage = '未知错误';

      //       // 在某些浏览器中，你可能能够通过以下方式获取状态码
      //       if (event.target.status) {
      //           errorMessage += ` (HTTP状态码: ${event.target.status})`;
      //       }

      //       console.error(errorMessage);
      //   }

      //   // 关闭连接

      // eventSource.close();
      // };
  }
  };
  const scrollContainer = ref(null)
  const scrollToBottom = () => {
    if (scrollContainer.value) {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
    }
  }
  
//   let rec = null;
// const recwave = ref(null);
// let wave = null;

// // 定义录音状态
const mediaRecorder = ref(null);// 媒体录制器
const audioChunks = ref([]);// 音频片段
const audioUrl = ref('');// 音频URL
const recognition = ref(null);// 语音识别器
const transcript = ref('');// 识别结果
const errorMessage = ref('');// 错误信息
const isRecording = ref(false);// 是否正在录音
const isPaused = ref(false);// 是否暂停
const audioContext = ref(null);// 音频上下文
const analyser = ref(null);// 分析器
const source = ref(null);// 音频源
const animationId = ref(null);// 动画ID
const monitorVolumeInterval = ref(null);

// // 根据录音状态动态设置图标
const recordingIcon = ref(markRaw(Microphone));
const tooltipContent=ref("语音输入")
const toggleVoice = async () => {
  isRecording.value = !isRecording.value;

  if (!isRecording.value) {
    recordingIcon.value = Microphone;
    tooltipContent.value = "语音输入";
    stopRecording();
  } else {
    recordingIcon.value = Mic;
    tooltipContent.value = "停止语音输入";
    startRecording();
  }
};

/**
 * 启动录音
 * @returns {Promise<void>}
 */
 const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    mediaRecorder.value = new MediaRecorder(stream);
    audioChunks.value = [];

    mediaRecorder.value.ondataavailable = (event) => {
      audioChunks.value.push(event.data);
    };

    mediaRecorder.value.onstop = () => {
      const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' });
      audioUrl.value = URL.createObjectURL(audioBlob);
    };

    mediaRecorder.value.start();
    startRecognition();

    audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
    analyser.value = audioContext.value.createAnalyser();
    source.value = audioContext.value.createMediaStreamSource(stream);
    source.value.connect(analyser.value);

    // 启动音量检测
    // monitorVolumeInterval.value = monitorVolume();
  } catch (error) {
    console.error('获取麦克风权限失败:', error);
  }
};

const stopRecording = () => {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop();
  }
  if (recognition.value) {
    recognition.value.stop();
  }
  if (audioContext.value && audioContext.value.state !== 'closed') {
    audioContext.value.close();
  }
  if (monitorVolumeInterval.value) {
    clearInterval(monitorVolumeInterval.value); // 清除定时器
    monitorVolumeInterval.value = null;
  }
  cancelAnimationFrame(animationId.value);
  isRecording.value = false;
  isPaused.value = false;
};
/**
 *  暂停录音
 */
 const pauseRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    mediaRecorder.value.pause();
    if (recognition.value) {
      recognition.value.stop();
    }
    isPaused.value = true;
  }
};

const resumeRecording = () => {
  if (mediaRecorder.value && isPaused.value) {
    mediaRecorder.value.resume();
    if (recognition.value) {
      startRecognition();
    }
    isPaused.value = false;
  }
};
/**
 * 检测麦克风音量
 */
 const monitorVolume = () => {
  const bufferLength = analyser.value.fftSize;
  const dataArray = new Uint8Array(bufferLength);

  const checkVolume = () => {
    analyser.value.getByteTimeDomainData(dataArray);
    let sum = 0;
    for (let i = 0; i < bufferLength; i++) {
      sum += (dataArray[i] - 128) * (dataArray[i] - 128);
    }
    const volume = Math.sqrt(sum / bufferLength);

    if (volume > 1) {
      isRecording.value = true;
      if (recognition.value && !isPaused.value && !isRecognitionActive) {
        startRecognition();
      }
    } else {
      isRecording.value = false;
    }
  };

  return setInterval(checkVolume, 100); // 每 100ms 检测一次
};

// 在 stopRecording 中清除定时器
// const stopRecording = () => {
//   if (mediaRecorder.value) {
//     mediaRecorder.value.stop();
//   }
//   if (recognition.value) {
//     recognition.value.stop();
//   }
//   if (audioContext.value && audioContext.value.state !== 'closed') {
//     audioContext.value.close();
//   }
//   clearInterval(monitorVolumeInterval.value); // 清除定时器
//   isRecording.value = false;
//   isPaused.value = false;
// };
/**
 * 启动语音识别
 */
let isRecognitionActive = false;

const startRecognition = () => {
  if (!isRecognitionActive) {
    recognition.value = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
    recognition.value.lang = 'zh-CN';
    recognition.value.continuous = true;
    recognition.value.interimResults = true;

    recognition.value.onresult = (event) => {
      let interimTranscript = '';
      for (let i = event.resultIndex; i < event.results.length; i++) {
        const transcriptPart = event.results[i][0].transcript;
        if (event.results[i].isFinal) {
          input.value += transcriptPart;
        } else {
          interimTranscript += transcriptPart;
        }
      }
    };

    recognition.value.onerror = (event) => {
      console.error('Recognition error:', event.error);
    };

    recognition.value.onend = () => {
      console.log('语音识别结束');
      isRecognitionActive = false;
      // 如果不是手动暂停，继续识别
      if (isRecording.value && !isPaused.value) {
        startRecognition();
      }
    };

    recognition.value.start();
    isRecognitionActive = true;
  }
};
/**
 * 停止录音
 */
//  const stopRecording = () => {
//   if (mediaRecorder.value) {
//     mediaRecorder.value.stop();
//   }
//   if (recognition.value) {
//     recognition.value.stop();
//   }
//   if (audioContext.value && audioContext.value.state !== 'closed') {
//     audioContext.value.close();
//   }
//   cancelAnimationFrame(animationId.value);
//   isRecording.value = false;
//   isPaused.value = false;
// };

onUnmounted(() => {
  if (audioContext.value && audioContext.value.state !== 'closed') {
    audioContext.value.close();
  }
  cancelAnimationFrame(animationId.value);
});



  onMounted(() => {
    initSpeech()
    if(counterStore.jwt){
      user.value=parseJwt(counterStore.jwt).claims
      setTimeout(() => {messageList.value.push({ id: 1, message: "等你好久了，终于来找我聊天了" });}, 1000);
    //   messageList.value.push({ id:1,message:"等你好久了，终于来找我聊天了😀😀"})
      scrollToBottom()
    }else{
        ElMessage({
    message: '您还未登录，请先前往登录！',
    type: 'warning',
  })
      router.push('/login')
    }
  
  })
  // 更新消息列表后滚动到底部
  onUpdated(() => {
    scrollToBottom()
  })
  
  const setDefaultImage = (event) => {
    event.target.src = 'https://p3fx.kgimg.com/v2/fxuserlogo/eac9145ecd909b9606c4f8e5f3e936e7.jpg_200x200.jpg'
  }
</script>
  
<style scoped>

.bo{
  width: 40vh;
  aspect-ratio: 1/1;
  background-color: #ffffff;
  position:absolute;
  top:20%;
  left: 40%;
  border-radius: 50%;
  /* z-index: 9999; */
}

.play-btn {
    margin-left: 8px;
    padding: 2px;
    vertical-align: middle;
    position: absolute;
    /* margin-right: auto; */
    /* float: right; */
    bottom: 0;
    right: 0;
    /* background-color: yellowgreen; */
    /* width: 30px; */
    &:hover {
        color: #409eff;
    }
}


.message {
    position: relative;
    display: inline-flex;
    align-items: center;
    /* background-color: #409eff; */
}

  ::-webkit-scrollbar {
    width: 10px;
  }
  ::-webkit-scrollbar-track {
    background-color: rgba(0, 0, 0, 0);
  }
  ::-webkit-scrollbar-thumb {
    background-color: #dbd2d2ac;
    border-radius: 3px;
  }
  .notice {
    text-align: center;
  }
  img {
    width: 100%;
    height: 100%;
  }
  .room {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    /* background-color: yellowgreen; */
  }
  .view {
    overflow: auto;
    width: 100%;
    height: calc(100% - 210px);
    background-color: rgb(227, 228, 227);
  }
  .other {
    margin: 10px;
    width: calc(100% - 30px);
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
  }
  .other .hImg {
    width: 35px;
    height: 35px;
    border-radius: 50%;
    margin-bottom: auto;
  }
  .other .message {
    position: relative;
    word-wrap: break-word;
    background-color: rgb(255, 255, 255);
    margin: 0 10px;
    border-radius: 6px;
    padding: 8px 12px;
    max-width: 300px;
    span{
      font-size: 13px;
      color: rgb(128, 128, 128);
      width: 200px;
      position: absolute;
      /* background-color: yellowgreen; */
      left: 105%;
      bottom: 0;
    }
  }
  .me {
    margin: 10px;
    width: calc(100% - 30px);
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
  .me .hImg {
    width: 35px;
    height: 35px;
    border-radius: 50%;
    margin-bottom: auto;
  }
  .me .message {
    word-wrap: break-word;
    background-color: rgba(28, 199, 42, 0.692);
    margin: 0 10px;
    border-radius: 6px;
    padding: 8px 12px;
    position: relative;
    max-width: 300px;
    span{
      font-size: 13px;
      color: rgb(128,128,128);
      width: 200px;
      position: absolute;
      right: 80%;
      top: 50%;
    }
  }
  .input {
    width: 100%;
    height: 200px;
  }
  
  :deep(.el-textarea__inner) {
    outline: none;
    border: none;
    resize: none;
    box-shadow: none;
  }
  
  .input-anniu {
    width: 50px;
    height: 50px;
    float: right;
    border-radius: 50%;
    margin-right: 20px;
    font-size: 24px;
    color: #fff;
    background-color: #d6d5de;
  }


  .recording-animation {
  
  position:absolute;
  top:30%;
  left: 40%;
  width: 25vh;
  aspect-ratio: 1/1;
    background-color: #c2b4b4;
    border-radius: 50%;
    animation: pulse 1.2s infinite;
    margin: 20px auto;
    text-align: center;
    color: white;
    font-size: 34px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px;
    cursor: pointer;
  }
  @keyframes pulse {
    0% {
      transform: scale(0.95);
      box-shadow:  0 0 0 10px #dbd2d2;
    }
    70% {
      transform: scale(1);
      box-shadow: 0 0 0 20px rgba(255, 0, 0, 0);
    }
    100% {
      transform: scale(0.95);
      box-shadow: 0 0 0 0 rgba(255, 0, 0, 0);
    }
  }
</style>